<template>
    <div class="order-complaint-management">
        <!-- 操作栏 -->
        <div class="operation-bar">
            <el-input
                v-model="searchText"
                placeholder="搜索投诉记录"
                style="width: 300px"
                clearable
            >
                <template #prefix>
                    <span style="margin-right: 8px">🔍</span>
                </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">
                <span style="margin-right: 5px">+</span>新增投诉记录
            </el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="filteredComplaints" border style="width: 100%">
            <el-table-column prop="orderId" label="订单编号" width="180" sortable />
            <el-table-column prop="buyerName" label="买家姓名" width="120" />
            <el-table-column prop="productName" label="商品名称" width="180" />
            <el-table-column prop="complaintType" label="投诉类型" width="150">
                <template #default="{ row }">
                    {{ complaintTypeOptions.find(t => t.value === row.complaintType)?.label }}
                </template>
            </el-table-column>
            <el-table-column prop="complaintDate" label="投诉时间" width="150">
                <template #default="{ row }">
                    {{ formatDate(row.complaintDate) }}
                </template>
            </el-table-column>
            <el-table-column prop="complaintContent" label="投诉内容" width="200">
                <template #default="{ row }">
                    <span v-if="row.complaintContent.length > 20">{{ row.complaintContent.slice(0, 20) }}...</span>
                    <span v-else>{{ row.complaintContent }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="处理状态" width="120">
                <template #default="{ row }">
                    <el-tag :type="statusType[row.status]">
                        {{ statusOptions.find(s => s.value === row.status)?.label }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="{ row }">
                    <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="isEditMode ? '编辑投诉记录' : '新增投诉记录'"
            width="600"
        >
            <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-width="80px"
            >
                <el-form-item label="订单编号" prop="orderId">
                    <el-input v-model="formData.orderId" :disabled="isEditMode" />
                </el-form-item>
                <el-form-item label="买家姓名" prop="buyerName">
                    <el-input v-model="formData.buyerName" />
                </el-form-item>
                <el-form-item label="商品名称" prop="productName">
                    <el-input v-model="formData.productName" />
                </el-form-item>
                <el-form-item label="投诉类型" prop="complaintType">
                    <el-select v-model="formData.complaintType" placeholder="请选择投诉类型">
                        <el-option
                            v-for="item in complaintTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="投诉时间" prop="complaintDate">
                    <el-date-picker
                        v-model="formData.complaintDate"
                        type="datetime"
                        placeholder="选择日期时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                    />
                </el-form-item>
                <el-form-item label="投诉内容" prop="complaintContent">
                    <el-input type="textarea" v-model="formData.complaintContent" rows="3" />
                </el-form-item>
                <el-form-item label="处理状态" prop="status">
                    <el-select v-model="formData.status" placeholder="请选择处理状态">
                        <el-option
                            v-for="item in statusOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 日期格式化（包含时间）
const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    }).replace(/\//g, '-')
}

// 投诉类型选项
const complaintTypeOptions = [
    { value: 'quality', label: '质量问题' },
    { value: 'description', label: '描述不符' },
    { value: 'shipping', label: '物流问题' },
    { value: 'service', label: '服务态度' },
    { value: 'other', label: '其他问题' }
]

// 处理状态选项
const statusOptions = [
    { value: 0, label: '待处理' },
    { value: 1, label: '处理中' },
    { value: 2, label: '已处理' }
]
const statusType = { 0: 'danger', 1: 'warning', 2: 'success' }

// 10条投诉记录测试数据
const complaints = ref([
    {
        id: 1,
        orderId: 'OD2024001',
        buyerName: '张三',
        productName: '二手笔记本电脑',
        complaintType: 'quality',
        complaintDate: '2024-04-15 14:30:00',
        complaintContent: '电脑无法开机，怀疑主板损坏',
        status: 0
    },
    {
        id: 2,
        orderId: 'OD2024002',
        buyerName: '李四',
        productName: '二手沙发',
        complaintType: 'description',
        complaintDate: '2024-04-16 10:15:00',
        complaintContent: '颜色与图片差异过大，实物偏暗',
        status: 1
    },
    {
        id: 3,
        orderId: 'OD2024003',
        buyerName: '王五',
        productName: '二手手机',
        complaintType: 'shipping',
        complaintDate: '2024-04-17 15:45:00',
        complaintContent: '物流显示签收但未收到商品',
        status: 2
    },
    {
        id: 4,
        orderId: 'OD2024004',
        buyerName: '赵六',
        productName: '二手相机',
        complaintType: 'service',
        complaintDate: '2024-04-18 09:30:00',
        complaintContent: '卖家拒绝提供售后退换服务',
        status: 0
    },
    {
        id: 5,
        orderId: 'OD2024005',
        buyerName: '孙七',
        productName: '二手自行车',
        complaintType: 'quality',
        complaintDate: '2024-04-19 16:20:00',
        complaintContent: '刹车失灵导致骑行时摔倒',
        status: 1
    },
    {
        id: 6,
        orderId: 'OD2024006',
        buyerName: '周八',
        productName: '二手书桌',
        complaintType: 'description',
        complaintDate: '2024-04-20 11:00:00',
        complaintContent: '尺寸标注错误，实际比描述小20cm',
        status: 2
    },
    {
        id: 7,
        orderId: 'OD2024007',
        buyerName: '吴九',
        productName: '二手冰箱',
        complaintType: 'shipping',
        complaintDate: '2024-04-21 17:10:00',
        complaintContent: '物流过程中导致冰箱外壳凹陷',
        status: 0
    },
    {
        id: 8,
        orderId: 'OD2024008',
        buyerName: '郑十',
        productName: '二手耳机',
        complaintType: 'service',
        complaintDate: '2024-04-22 08:45:00',
        complaintContent: '卖家未按约定时间发货',
        status: 1
    },
    {
        id: 9,
        orderId: 'OD2024009',
        buyerName: '王十一',
        productName: '二手洗衣机',
        complaintType: 'quality',
        complaintDate: '2024-04-23 13:30:00',
        complaintContent: '洗衣机运转时发出异常噪音',
        status: 2
    },
    {
        id: 10,
        orderId: 'OD2024010',
        buyerName: '李十二',
        productName: '二手书籍',
        complaintType: 'other',
        complaintDate: '2024-04-24 14:00:00',
        complaintContent: '商品缺少配套说明书和配件',
        status: 0
    }
])

// 搜索功能（支持多字段模糊搜索）
const searchText = ref('')
const filteredComplaints = computed(() => {
    const searchKey = searchText.value.toLowerCase()
    return complaints.value.filter(complaint => {
        return [
            complaint.orderId,
            complaint.buyerName,
            complaint.productName,
            complaint.complaintContent,
            complaintTypeOptions.find(t => t.value === complaint.complaintType)?.label
        ].join('').toLowerCase().includes(searchKey)
    })
})

// 对话框状态管理
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
    id: null,
    orderId: '',
    buyerName: '',
    productName: '',
    complaintType: 'quality', // 默认投诉类型
    complaintDate: new Date().toISOString().split('.')[0], // 包含时间的默认值
    complaintContent: '',
    status: 0 // 默认待处理状态
})

// 表单验证规则
const formRules = {
    orderId: [{ required: true, message: '请输入订单编号', trigger: 'blur' }],
    buyerName: [{ required: true, message: '请输入买家姓名', trigger: 'blur' }],
    productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
    complaintType: [{ required: true, message: '请选择投诉类型', trigger: 'change' }],
    complaintDate: [{ required: true, message: '请选择投诉时间', trigger: 'change' }],
    complaintContent: [{ required: true, message: '请填写投诉内容', trigger: 'blur' }],
    status: [{ required: true, message: '请选择处理状态', trigger: 'change' }]
}

// 操作函数
const handleAdd = () => {
    isEditMode.value = false
    resetForm()
    dialogVisible.value = true
}

const handleEdit = (row) => {
    isEditMode.value = true
    Object.assign(formData, { ...row })
    dialogVisible.value = true
}

const handleDelete = (id) => {
    ElMessageBox.confirm('确定要删除该投诉记录吗？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        complaints.value = complaints.value.filter(c => c.id !== id)
        ElMessage.success('删除投诉记录成功')
    })
}

const submitForm = async () => {
    await formRef.value.validate()
    if (isEditMode.value) {
        const index = complaints.value.findIndex(c => c.id === formData.id)
        complaints.value.splice(index, 1, { ...formData })
    } else {
        complaints.value.push({
            ...formData,
            id: Date.now(),
            complaintDate: formData.complaintDate || new Date().toISOString().split('.')[0]
        })
    }
    dialogVisible.value = false
}

const resetForm = () => {
    formData.id = null
    formData.orderId = ''
    formData.buyerName = ''
    formData.productName = ''
    formData.complaintType = 'quality'
    formData.complaintDate = new Date().toISOString().split('.')[0]
    formData.complaintContent = ''
    formData.status = 0
}
</script>

<style scoped>
.order-complaint-management {
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.operation-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
}

.el-table {
    margin-top: 20px;
}

.el-tag {
    font-weight: 500;
}

.el-textarea__inner {
    height: 80px; /* 调整文本域高度 */
}
</style>